package com.fengwk.support.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import com.fengwk.support.exception.BaseException;
import com.fengwk.support.util.LoggerUtils.Logger;


/**
 * 工具类:操作Properties属性文件
 */
public final class PropertiesUtils {
	
	private static final Logger LOG = LoggerUtils.getLogger(PropertiesUtils.class);
	
	private static final String character = "utf-8";
	
	private PropertiesUtils() {
		throw new BaseException("can not instance " + getClass());
	}
	
	/**
	 * 通过路径构造并返回Properties对象
	 * 
	 * @param propertiesPath Properties属性文件的决对路径/类路径
	 */
	public static Properties initPropertiesByPath(String propertiesPath) throws Exception{
		Properties properties = new Properties();
		try {
			properties.load(getCharsetReader(PropertiesUtils.class.getClassLoader().getResourceAsStream(propertiesPath)));
			if(properties == null || properties.size() == 0){
				try {
					if(initPropertiesByPathSecond(properties, propertiesPath) == null){
						throw new Exception("Properties加载配置文件失败");
					}else{
						return properties;
					}
				} catch (Exception e) {
					properties = null;
					LOG.error(e);
					throw new Exception("Properties加载配置文件失败");
				}
			}
		} catch (Exception e) {
			try {
				if(initPropertiesByPathSecond(properties, propertiesPath) == null){
					throw new Exception("Properties加载配置文件失败");
				}else{
					return properties;
				}
			} catch (Exception e2) {
				properties = null;
				LOG.error(e);
				throw new Exception("Properties加载配置文件失败");
			}
		}
		return properties;
	}
	//次级策略(通过路径加载)
	private static Properties initPropertiesByPathSecond(Properties properties, 
			String propertiesPath) {
		FileInputStream fis = null;
		try {
			properties.load(getCharsetReader(new FileInputStream(propertiesPath)));
		} catch (Exception e) {
		    LOG.error(e);
			return null;
		} finally{
			if (fis != null){
				try {
					fis.close();
				} catch (IOException e) {
				    LOG.error(e);
				}
			}
		}
		return properties;
	}
	
	/**
	 * 获取字符集编码的reader
	 */
	private static Reader getCharsetReader(InputStream in) throws UnsupportedEncodingException {
		return new InputStreamReader(in, character);
	}
	
}
